﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;

namespace SPSource2010
{
    public static class Utility
    {
        public static DirectoryInfo CurrentExecutingDirectory
        {
            get
            {
                DirectoryInfo currentExecutingDirectory = new DirectoryInfo(Environment.CurrentDirectory);
                return currentExecutingDirectory;
            }
        }

        public static DirectoryInfo CurrentFeatureRootDirectory(FileInfo spSourceFile)
        {
            return CurrentFeatureRootDirectory(spSourceFile.Directory);            
        }

        public static DirectoryInfo CurrentFeatureRootDirectory(DirectoryInfo spSourceFileDirectory)
        {
            DirectoryInfo featureDirectory = spSourceFileDirectory;
            //DirectoryInfo currentExecutingDirectory = new DirectoryInfo(Environment.CurrentDirectory);

            //while (featureDirectory.GetFiles("feature.xml").Length == 0)
            //{
            //    if (featureDirectory.FullName == Utility.CurrentExecutingDirectory.FullName)
            //    {
            //        throw new Exception("Your Feature directory must contain a Feature.xml file to function properly");
            //    }
            //    featureDirectory = featureDirectory.Parent;
            //}

            return featureDirectory;
        }

        public static string GetRelativePathToSPSourceFileFromFeatureRoot(DirectoryInfo directory, DirectoryInfo featureDirectory)
        {
            string relativePath = string.Empty;
            string spSourceDirectory = directory.FullName;

            //get the relative path to the SpSource file from the location of the feature.xml file
            relativePath = spSourceDirectory.Replace(featureDirectory.FullName, "");
            if (relativePath.StartsWith("\\"))
                relativePath = relativePath.Remove(0, 1);

            return relativePath;
        }

        private const string divider = "\n---------------------------------------------\n";
        public static void WriteMessage(string message)
        {
            WriteMessage(string.Format("INFO: {0}", message), string.Empty);
        }

        public static void WriteMessage(string message, string sectionName)
        {
            StringBuilder sb = new StringBuilder();
            if (!String.IsNullOrEmpty(sectionName))
                sb.AppendFormat("{0}{1}{0}", divider, sectionName);
            sb.Append(message);
            Console.WriteLine(sb.ToString());
        }

        public static void WriteError(string message)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("ERROR: {0}", message);
            Console.WriteLine(sb.ToString());
        }
    }
}
